package com.xbh.management.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xbh.common.utils.JwtUtil;
import com.xbh.common.web.core.Result;
import com.xbh.management.enums.AttendanceTypeEnum;
import com.xbh.management.model.ManAttendance;
import com.xbh.management.model.ManLeave;
import com.xbh.management.service.AttendanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @program: management-center
 * @description:
 * @author: 许宝华
 * @create: 2022-03-08 16:29
 */
@RestController
@RequestMapping("/attendance")
public class AttendanceController {

    @Autowired
    private AttendanceService attendanceService;

    @PostMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public Result save(@RequestBody JSONObject params) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String startTime = simpleDateFormat.format(new Date());
        String subTime = startTime.substring(0, 10);

        String start = "00:00:01";
        String end = "23:59:59";

        String clockTime = "09:30:00";
        //最迟打卡时间
        String newTime = subTime+ " " + clockTime;
        //一天开始时间
        String startData = subTime+ " " + start;
        //一天结束时间
        String endData = subTime+ " " + end;

        //最迟打卡时间
        Date cardTime = simpleDateFormat.parse(newTime);

        //当前打卡时间
        Date currentTime = params.getDate("startTime");


        ManAttendance manAttendance = params.toJavaObject(ManAttendance.class);

        LambdaQueryWrapper<ManAttendance> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ManAttendance::getUserId, JwtUtil.getUserId());
        wrapper.and(
                LambdaQueryWrapper -> LambdaQueryWrapper.eq(ManAttendance::getAttendanceType, AttendanceTypeEnum.PUNCH_CARD.getCode())
                        .or()
                        .eq(ManAttendance::getAttendanceType,AttendanceTypeEnum.LATE_PUNCH_CARD.getCode())
                        .or()
                        .eq(ManAttendance::getAttendanceType,AttendanceTypeEnum.NO_PUNCH_CARD.getCode())
                        .or()
                        .eq(ManAttendance::getAttendanceType,AttendanceTypeEnum.LEAVE.getCode())
        );
        wrapper.between(ManAttendance::getStartTime,simpleDateFormat.parse(startData),simpleDateFormat.parse(endData));
        List<ManAttendance> list = attendanceService.list(wrapper);
        if(CollectionUtil.isNotEmpty(list)){
            ManAttendance attendance = list.get(0);
            //上班打卡时间
            Date workTime = attendance.getStartTime();
            Calendar Cal=Calendar.getInstance();
            Cal.setTime(workTime);
            Cal.add(Calendar.HOUR_OF_DAY,9);
            //允许下班的时间
            Date  closedTime = Cal.getTime();
            if(currentTime.before(closedTime)){
                return Result.failed("早退！不可打卡");
            }
            if(currentTime.after(closedTime)){
                attendance.setEndTime(currentTime);
                attendance.setWorkTime((((currentTime.getTime() - workTime.getTime()) / (60 * 60 * 1000)) % 24));
                boolean flag = attendanceService.updateById(attendance);
                if(flag){
                    return Result.success("下班打卡成功");
                }
                return Result.failed("下班打卡失败,请重新打卡");
            }
            return Result.failed("您已经打卡成功，不可重复打卡");
        }

        //当前时间在9:30之前 打卡正常
        if (currentTime.before(cardTime)) {
            manAttendance.setAttendanceType(AttendanceTypeEnum.PUNCH_CARD.getCode());
        }
        //当前时间在9:30之后 迟到
        if (currentTime.after(cardTime)) {
            manAttendance.setAttendanceType(AttendanceTypeEnum.LATE_PUNCH_CARD.getCode());
        }

        boolean flag = attendanceService.saveAttendance(manAttendance);
        if(flag){
            return Result.success("打卡成功");
        }
        return Result.failed("保存失败");
    }

    @PostMapping("/page")
    public Result page(@RequestBody JSONObject params){
        ManAttendance manAttendance = params.toJavaObject(ManAttendance.class);
        int pageNum = params.getInteger("pageNum");
        int pageSize = params.getInteger("pageSize");
        IPage<ManAttendance> list = attendanceService.list(new Page<ManAttendance>(pageNum, pageSize), manAttendance);
        return Result.success(list);
    }

}
